package com.example.weight.greenSeasons.compost;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.config.Config;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import net.cachapa.expandablelayout.ExpandableLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CompostDailyInspectorActivity_old extends AppCompatActivity {

    //用户、抄表人
    private String username, factory;
    
    private List<CheckBox> checkBoxes;
    private List<String> ids, remarks;
    private List<Integer> textViews;

    private ExpandableLayout expandable_1;
    private Button ButtonNo1;
    private ExpandableLayout expandable_2;
    private Button ButtonNo2;
    private ExpandableLayout expandable_3;
    private Button ButtonNo3;

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_compost_daily_inspector_old);

        Intent previousIntent = getIntent();
        username = previousIntent.getStringExtra("name");
        factory = previousIntent.getStringExtra("factory");

        TitleBar titleBar = findViewById(R.id.titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {finish();}

            @Override
            public void onTitleClick(View v) {}

            @Override
            public void onRightClick(View v) {}
        });

        TextView dateEdit = findViewById(R.id.worm_incoming_incomeDate);
        Calendar calendar=Calendar.getInstance();
        Integer year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH)+1; //第一个月从0开始，所以得到月份＋1
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        dateEdit.setText(year+"-"+month+"-"+day);

        expandable_1 = findViewById(R.id.expandable_1);
        ButtonNo1 = findViewById(R.id.button1);
        expandable_2 = findViewById(R.id.expandable_2);
        ButtonNo2 = findViewById(R.id.button2);
        expandable_3 = findViewById(R.id.expandable_3);
        ButtonNo3 = findViewById(R.id.button3);

        //勾选
        CheckBox checkBox1 = findViewById(R.id.checkBox1);
        checkBox1.setEnabled(false);
        CheckBox checkBox2 = findViewById(R.id.checkBox2);
        checkBox2.setEnabled(false);
        CheckBox checkBox3 = findViewById(R.id.checkBox3);
        checkBox3.setEnabled(false);
        CheckBox checkBox4 = findViewById(R.id.checkBox4);
        checkBox4.setEnabled(false);
        CheckBox checkBox5 = findViewById(R.id.checkBox5);
        checkBox5.setEnabled(false);
        CheckBox checkBox6 = findViewById(R.id.checkBox6);
        checkBox6.setEnabled(false);
        CheckBox checkBox7 = findViewById(R.id.checkBox7);
        checkBox7.setEnabled(false);
        CheckBox checkBox8 = findViewById(R.id.checkBox8);
        checkBox8.setEnabled(false);
        CheckBox checkBox9 = findViewById(R.id.checkBox9);
        checkBox9.setEnabled(false);
        CheckBox checkBox10 = findViewById(R.id.checkBox10);
        checkBox10.setEnabled(false);

        checkBoxes = new ArrayList<>();
        checkBoxes.add(checkBox1);
        checkBoxes.add(checkBox2);
        checkBoxes.add(checkBox3);
        checkBoxes.add(checkBox4);
        checkBoxes.add(checkBox5);
        checkBoxes.add(checkBox6);
        checkBoxes.add(checkBox7);
        checkBoxes.add(checkBox8);
        checkBoxes.add(checkBox9);
        checkBoxes.add(checkBox10);
        ids = new ArrayList<>();
        remarks = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            ids.add("-100");
            remarks.add("");
        }
        textViews = new ArrayList<>();
        textViews.add(R.id.equipment1_state);
        textViews.add(R.id.equipment2_state);
        textViews.add(R.id.equipment3_state);
        textViews.add(R.id.equipment4_state);
        textViews.add(R.id.equipment5_state);
        textViews.add(R.id.equipment6_state);
        textViews.add(R.id.equipment7_state);
        textViews.add(R.id.equipment8_state);
        textViews.add(R.id.equipment9_state);
        textViews.add(R.id.equipment10_state);

        //获取当天最新一条数据
        RequestQueue queue = Volley.newRequestQueue(this);
        String url = Config.url + "/shlj/sjqCompostProduceMaintenance/getDailyRecords" + "?factory=" + factory;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            JSONArray data;
                            if(!jsonObject.isNull("data")) {
                                data = jsonObject.getJSONArray("data");
                                if(data.length() > 0){
                                    for(int i = 0; i < data.length(); i++){
                                        // 遍历 jsonarray 数组，把每一个对象转成 json 对象
                                        JSONObject record = data.getJSONObject(i);
                                        // 得到 每个对象中的属性值
                                        for (int j = 0; j < checkBoxes.size(); j++) {
                                            CheckBox checkBox = checkBoxes.get(j);
                                            if (record.getString("equipmentName").
                                                    equals(checkBox.getText().toString())) {
                                                if (!record.isNull("inspector")) {
                                                    checkBox.setChecked(true);
                                                    checkBox.setEnabled(false);
                                                    checkBox.setTextColor(Color.GREEN);
                                                } else
                                                    checkBox.setEnabled(true);
                                                ids.set(j, record.getString("id"));
                                                int textViewId = textViews.get(j);
                                                if(record.get("isNormal").equals("正常")){
                                                    TextView text = findViewById(textViewId);
                                                    text.setText("正常");
                                                    text.setTextColor(Color.parseColor("#018786"));
                                                }else {
                                                    TextView text = findViewById(textViewId);
                                                    String remark = record.getString("remarks");
                                                    text.setText(remark);
                                                    remarks.set(j, remark);
                                                    text.setTextColor(Color.parseColor("#B00020"));
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            for (int i = 0; i < checkBoxes.size(); i++) {
                                int counter = i;
                                CheckBox checkBox = checkBoxes.get(i);
                                String id = ids.get(i);
                                checkBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
                                    if (isChecked)
                                        checkEquipment(checkBox, id, counter);
                                });
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(CompostDailyInspectorActivity_old.this,
                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);
    }

    public void checkEquipment(CheckBox equipment_name,String id,int counter) {
        final EditText equipment_problem = new EditText(this);
        equipment_problem.setHint("   输入问题:");
        new AlertDialog.Builder(this)
                .setTitle("操作人结论是否正确？如果有误请在下方填写问题")
                .setView(equipment_problem)
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) ->{
                    Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show();
                    equipment_name.setChecked(false);
                }
                ))
                .setPositiveButton("提交", (dialog, which) ->{
                    // 提交表单
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/shlj/sjqCompostProduceMaintenance/add_day_inspector";

                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @SuppressLint("SetTextI18n")
                                @Override
                                public void onResponse(String response) {
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");
                                        if (code.equals("200")){
                                            Toast.makeText(CompostDailyInspectorActivity_old.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                            equipment_name.setEnabled(false);
                                            if (!equipment_problem.getText().toString().equals("")) {
                                                TextView textView = findViewById(textViews.get(counter));
                                                textView.setText(textView.getText().toString()+" "+
                                                        equipment_problem.getText().toString());
                                            }
                                        }
                                        else {
                                            Toast.makeText(CompostDailyInspectorActivity_old.this,
                                                    "1保存失败", Toast.LENGTH_SHORT).show();
                                            equipment_name.setChecked(false);
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(CompostDailyInspectorActivity_old.this,
                                    "2保存失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() {
                            String temp = remarks.get(counter);
                            if (!equipment_problem.getText().toString().equals(""))
                                temp += "_"+equipment_problem.getText().toString();
                            Map<String, String> map=new HashMap<>();
                            map.put("id", id);   ///------------------------这里要id
                            map.put("Inspector", username);
                            map.put("remarks", temp);
                            map.put("factory", factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                })
                .show();
    }

    public void show1(View view) {
        if (expandable_1.isExpanded()){
            ButtonNo1.setText("+ 检查运行状况");
        }else{
            ButtonNo1.setText("- 检查运行状况");
        }
        expandable_1.toggle();
    }
    public void show2(View view) {
        if (expandable_2.isExpanded()){
            ButtonNo2.setText("+ 擦拭卫生");
        }else{
            ButtonNo2.setText("- 擦拭卫生");
        }
        expandable_2.toggle();
    }
    public void show3(View view) {
        if (expandable_3.isExpanded()){
            ButtonNo3.setText("+ 擦拭检查噪音");
        }else{
            ButtonNo3.setText("- 擦拭检查噪音");
        }
        expandable_3.toggle();
    }
}